<template>
  <div class="basicForm">
    <BasicForm @register="registerForm">
      <!-- 插槽（备注信息） -->
      <template #remarks="{ model, field }">
        <WangEditor
          v-model:value="model[field]"
          :bizKey="record.id"
          :bizType="'testDataChild_' + field"
          :height="300"
        />
      </template>
      <template #rdsSelect>
        <ListSelect
          v-model:value="itemCodes"
          :labelValue="itemNames"
          :selectType="props.selectType"
          :checkbox="true"
          :params="queryParams"
          @select="handSelect"
        />
      </template>
      <template #m8OrderFlowFhRdsList>
        <BasicTable
          @register="registerM8OrderFlowFhRdsTable"
          @row-click="handleM8OrderFlowFhRdsRowClick"
        />
        <a-button
          v-if="record.allowEdit"
          class="mt-2"
          @click="handleM8OrderFlowFhRdsAdd"
          v-auth="'order:flow:fh:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTestTestDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, watch } from 'vue';
  // import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { M8OrderFlowFh } from '/@/api/m8/order/flow/fh/m8OrderFlowFh';
  import { WangEditor } from '/@/components/WangEditor';
  import { formSchemas } from '/@/utils/custom';
  import { t } from '/@/hooks/web/useI18n';
  import { BasicTable, useTable } from '/@/components/Table';
  import { ListSelect } from '/@/components/ListSelect';

  const props = defineProps({
    schemas: { type: Array, default: [] },
    data: { type: Object, default: {} },
    formConfig: { type: Object, default: {} },
    selectType: { type: String as PropType<string> },
  });
  let inputFormSchemas: FormSchema[] = [];
  watch(
    () => props,
    () => {
      inputFormSchemas = formSchemas(
        props.schemas,
        props.formConfig.formColNum,
        props.data,
      ) as FormSchema[];

      setTimeout(() => {
        zdy(props.data);
      }, 0);
    },
    { immediate: true },
  );

  const record = ref<M8OrderFlowFh>({} as M8OrderFlowFh);
  const itemCodes = ref('');
  const itemNames = ref('');
  const queryParams = ref({
    'oper.operCode': 'FH',
    'djNo.bred': '0',
  });

  const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm();
  async function zdy(data) {
    setProps({
      labelWidth: 120, // 控件前面的标签宽度
      schemas: inputFormSchemas, // 控件定义列表
      baseColProps: { lg: parseInt(props.formConfig.formColNum), md: 24 },
    });
    await resetFields(); // 重置表单数据
    record.value = data;
    await setFieldsValue(data); // 设置字段值
    setM8OrderFlowFhRdsTableData(data);
  }

  async function validateForm() {
    try {
      const data = await validate(); // 验证表单，并返回数据
      data.m8OrderFlowFhRdsList = await getM8OrderFlowFhRdsList();
      return data;
    } catch (error: any) {
      if (error && error.errorFields) {
        return false;
      }
    }
  }

  defineExpose({
    validateForm,
  });

  const [registerM8OrderFlowFhRdsTable, m8OrderFlowFhRdsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleM8OrderFlowFhRdsDelete.bind(this, record1),
          },
          auth: 'order:flow:fh:edit',
          ifShow: record.value.allowEdit,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setM8OrderFlowFhRdsTableData(_res: Recordable) {
    m8OrderFlowFhRdsTable.setColumns([
      {
        title: t('订单ID'),
        dataIndex: 'order.id',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
        ifShow: false,
      },
      {
        title: t('图纸ID'),
        dataIndex: 'orderPic.id',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('流程ID'),
        dataIndex: 'orderFlow.id',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: true,
        ifShow: false,
      },
      {
        title: t('图号'),
        dataIndex: 'orderPic.picno',
        width: 100,
        align: 'left',
      },
      {
        title: t('图名'),
        dataIndex: 'orderPic.picname',
        width: 200,
        align: 'left',
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
          require: true,
        },
        editRule: (text: any, record: Recordable) => {
          return new Promise((resolve, reject) => {
            let iqty = Number(text);
            if (!isNaN(iqty)) {
              if (props.data.bred === '1' && iqty > 0) {
                reject('退货数量应为负数！');
              } else {
                resolve();
              }
            } else {
              reject('数量输入有误！');
            }
          });
        },
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 1000,
        },
        editRule: false,
      },
      {
        title: t('订单号'),
        dataIndex: 'order.ccode',
        width: 100,
        align: 'left',
      },
    ]);
    m8OrderFlowFhRdsTable.setTableData(record.value.m8OrderFlowFhRdsList || []);
  }

  function handleM8OrderFlowFhRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handSelect(selectData) {
    selectData.forEach((item) => {
      m8OrderFlowFhRdsTable.insertTableDataRecord({
        id: '',
        isNewRecord: true,
        editable: true,
        ...item,
        iqty:
          item.iqty - ((props.selectType === 'flowSelect' ? item.overQty : item.sumBackQty) || 0),
      });
    });
  }

  function handleM8OrderFlowFhRdsAdd() {
    document.getElementById('form_item_selIds')?.click();
  }

  function handleM8OrderFlowFhRdsDelete(record: Recordable) {
    m8OrderFlowFhRdsTable.deleteTableDataRecord(record);
  }

  async function getM8OrderFlowFhRdsList() {
    let m8OrderFlowFhRdsListValid = true;
    let m8OrderFlowFhRdsList: Recordable[] = [];
    for (const record of m8OrderFlowFhRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        m8OrderFlowFhRdsListValid = false;
      }
      m8OrderFlowFhRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of m8OrderFlowFhRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      m8OrderFlowFhRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!m8OrderFlowFhRdsListValid) {
      throw { errorFields: [{ name: ['m8OrderFlowFhRdsList'] }] };
    }
    return m8OrderFlowFhRdsList;
  }
</script>
<style>
  .col {
    color: red;
    font-weight: 100;
  }
</style>
